// sm2gmssl.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <gmssl/sm2.h>
#include <gmssl/sm3.h>   // 确保包含此头文件
#include <gmssl/error.h>

int main(void) {
    // 1. 生成 SM2 密钥对
    SM2_KEY sm2_key;
    if (sm2_key_generate(&sm2_key) != 1) {
        fprintf(stderr, "Failed to generate SM2 key\n");
        return -1;
    }

    // 2. 原始消息
    const char *msg = "Hello, SM2 from GmSSL!";
    size_t msg_len = strlen(msg);

    // 3. 使用 SM3_CTX 计算 SM3 摘要
    uint8_t dgst[SM3_DIGEST_SIZE]; // 32 bytes
    SM3_CTX sm3_ctx;
    sm3_init(&sm3_ctx);
    sm3_update(&sm3_ctx, (const uint8_t *)msg, msg_len);
    sm3_finish(&sm3_ctx, dgst);

    // 4. SM2 加密
    uint8_t ciphertext[512];
    size_t ciphertext_len;
    if (sm2_encrypt(&sm2_key, (const uint8_t *)msg, msg_len, ciphertext, &ciphertext_len) != 1) {
        fprintf(stderr, "SM2 encryption failed\n");
        return -1;
    }
    printf("SM2 encryption succeeded. Ciphertext length: %zu\n", ciphertext_len);

    // 5. SM2 解密
    uint8_t plaintext[512];
    size_t plaintext_len;
    if (sm2_decrypt(&sm2_key, ciphertext, ciphertext_len, plaintext, &plaintext_len) != 1) {
        fprintf(stderr, "SM2 decryption failed\n");
        return -1;
    }
    plaintext[plaintext_len] = '\0';
    printf("Decrypted text: %s\n", plaintext);

    // 6. SM2 签名（对 dgst 签名）
    uint8_t signature[SM2_MAX_SIGNATURE_SIZE];
    size_t sig_len;
    if (sm2_sign(&sm2_key, dgst, signature, &sig_len) != 1) {
        fprintf(stderr, "SM2 signing failed\n");
        return -1;
    }
    printf("SM2 signature succeeded. Signature length: %zu\n", sig_len);

    // 7. SM2 验签
    if (sm2_verify(&sm2_key, dgst, signature, sig_len) != 1) {
        fprintf(stderr, "SM2 verification failed\n");
        return -1;
    }
    printf("SM2 signature verified successfully!\n");

    return 0;
}
